<?php


namespace App\Helpers;


use App\Models\ActionLog;
use App\Models\Divide\City;
use App\Models\Divide\CitySplitRatio;
use App\Models\Divide\Department;
use App\Models\Divide\DepartmentSplitRatio;
use App\Models\Divide\DepartmentSplitRatioLog;
use App\Models\Divide\PdLevel;
use App\Models\Divide\PdOrder;
use App\Models\Divide\PdPdLog;
use App\Models\Divide\PdUserRelationship;
use App\Models\Divide\PersonSplitRatio;
use App\Models\Mch\RegisterCode;
use Carbon\Carbon;

trait CommisionTrait
{
    protected function selectLevelById($threshold,$mode){
        return PdLevel::query()
            ->where('threshold','<=',$threshold)
            ->where('mode',$mode)
            ->orderByDesc('threshold')
            ->first();
    }
    // 获取订单
    protected function getOrder($orderId){
        return PdOrder::query()->where('order_id',$orderId)->first();
    }
    private function bcRoundDown($num, $scale = 2) {
        $factor = bcpow('10', (string)$scale, 0);
        return bcdiv(bcmul($num, $factor, 0), $factor, $scale);
    }

    // 获取购买订单的用户
    protected function getUser($openid){
        $user = PdUserRelationship::query()
            ->where('uid',$openid)->where('role',3)->first();
        return $user;
    }
    /**
     * 设置用户待到账金额
     * @param $user_id
     * @param $money
     * @return void
     */
    protected function setUserWaittionMoney($user,$money,$order,$department_id){
        $pduser = PdUserRelationship::query()
            ->where('nid',$user->user_id)
            ->where('role',3)
            ->first();

        if($pduser){
            $finalMoney = bcadd($user->waitting_money, $money, 2);
            $pduser->waitting_money = $finalMoney;
            // 分账记录
            $this->divideLog($pduser,$order,$money,$department_id);
            $pduser->save();
        }

    }
    protected function divideLog($user,$order,$money,$department){
        $log = [
            'uid'=>$user->uid,
            'gid'=>$user->gid,
            'pid'=>$user->pid,
            'sid'=>$order->account_mode,
            'name'=>$user->name,
            'money'=>$money,
            'role'=>$user->role,
            'order_id'=>$order->order_id,
            'order_sid'=>$order->id,
            'mid'=>$department,
            'avatar'=>$user->avatar,
            'level'=>0,
            'surplusMoney'=>$money,
            'allMoney'=>$order->divide_money,
        ];
        // 创建日志记录
        PdPdLog::query()->create($log);
    }

    // 整除
    protected function divideAmount($amount, $divisor = 4) {
        // 处理空值
        $amount = $amount ?? '0.00';

        // 转换为字符串并标准化
        $amount = number_format((float)$amount, 2, '.', '');
        $divisor = number_format((float)$divisor, 2, '.', '');

        // 检查除数是否为零
        if (bccomp($divisor, '0.00', 2) === 0) {
            return '0.00';
        }

        return bcdiv($amount, $divisor, 2);
    }
    /**
     * 精确计算金额（向下取整）
     * @param string $money 金额字符串
     * @param string $ratio 比例字符串
     * @return string 计算结果（保留2位小数）
     */
    function calculateMoney($money, $ratio) {
        // 先进行乘法运算（保留4位小数保证精度）
        $result = bcmul($money, $ratio, 4);

        // 实现向下取整到2位小数
        $temp = bcmul($result, '100', 0);  // 先乘以100并截断小数
        $newMoney = bcdiv($temp, '100', 2); // 再除以100得到2位小数

        return $newMoney;
    }
    /**
     * 安全的高精度金额相减
     * @param string $a 被减数
     * @param string $b 减数
     * @param int $scale 保留小数位数
     * @return string 减法结果
     */
    protected function safeSubtract($a, $b, $scale = 2) {
        // 验证输入是否为合法数字字符串
        if (!is_numeric($a) || !is_numeric($b)) {
            throw new InvalidArgumentException('参数必须是有效数字字符串');
        }

        return bcsub($a, $b, $scale);
    }
    private function bcAbs($num) {
        if (bccomp($num, '0', 2) < 0) {
            return substr($num, 1);
        }
        return $num;
    }
    protected function addAmounts($amount1, $amount2, $scale = 2) {
        // 处理空值情况
        $amount1 = $amount1 ?? '0.00';
        $amount2 = $amount2 ?? '0.00';

        // 转换为字符串并格式化
        $amount1 = number_format((float)$amount1, $scale, '.', '');
        $amount2 = number_format((float)$amount2, $scale, '.', '');

        return bcadd($amount1, $amount2, $scale);
    }


    public function setCityLevel(){
        $citys = City::query()
            ->where('pid',0)
            ->get();
        foreach ($citys as $city){
            $city->level = 1;
            $city->save();
            $second = City::query()
                ->where('pid',$city->area_code)
                ->get();
            foreach ($second as $item){
                $item->level = 2;
                $item->save();
                City::query()
                    ->where('pid',$item->area_code)
                    ->update(['level'=>3]);

            }
        }
        return $this->success('成功');
    }


}

